// 源插件
import React, { PureComponent } from 'react';
import {
  DateDiff,
  DateStamp,
  FormatnumberZero,
  Mover,
  NumberDivide,
  GetDateThree,
} from '@/function.js';
// 视图插件
import { Button, Card, Col, Form, notification, Row, DatePicker, Select } from 'antd';
import { TimelineChartFour, TimelineChartFourMonth } from '@/components/Charts';

import html2canvas from 'html2canvas';
// 外部组件
import Loading from '@/components/Loading/Loading';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTablePro from '@/components/UpgradeReportStandardTable/StandardTablePro';
import { connect } from 'dva';
// css OR less预编译器

// 图片

const { Option } = Select;

/**
 *  Describe:数据连接
 */
function dataURLtoFile(dataurl, filename) {
  const arr = dataurl.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
}
@connect(({ fourfunds, loading }) => ({
  fourfunds,
  loading: loading.models.fourfundsRule,
}))
@Form.create()
class Summary extends PureComponent {
  componentWillMount() {}

  /**
   *  Describe:当前状态
   */

  state = {
    listLoading: false, // 加载状态
    dataSourceSC: {
      data: [],
      total: [],
      code: 0,
    },
    dataSourceSP: {
      data: [],
      total: [],
      code: 0,
    },
    dataSourceStock: {
      data: [],
      total: [],
      code: 0,
    },
    dataSourceDay: {
      data: [],
      total: [],
      code: 0,
    },
    cropFlag: false,
    date: '',
  };

  dataSourceChangeDay(date) {
    const { dispatch } = this.props;
    const that = this;
    dispatch({
      type: 'fourfunds/GetFundLastDayInfo',
      payload: {
        date,
      },
      callback: res => {
        const { data } = res;
        that.setState({
          dataSourceDay: {
            title: `四号基金账户汇总表 ${data.stock.date.split(' ')[0]} 汇总表`,
            total: [],
            titleTotal: false,
            data: [
              {
                name: '个股',
                marketvalue: data.stock.marketvalue,
                positionprofit: data.stock.onhandprofit,
                dayprofit: data.stock.todayprofit,
                historyprofit: data.stock.historyprofit,
                premiumscollect: data.stock.pendingpremium,
                profit: data.stock.profit,
                profitmarket: data.stock.profitratio,
                profitpercent: data.stock.profitpercent,
                positionpercent: data.stock.positionpercent,
                highpremiums: data.stock.highpremium,
              },
              {
                name: 'Sell Call',
                marketvalue: data.sc.marketvalue,
                positionprofit: data.sc.onhandprofit,
                dayprofit: data.sc.todayprofit,
                historyprofit: data.sc.historyprofit,
                premiumscollect: data.sc.pendingpremium,
                profit: data.sc.profit,
                profitmarket: data.sc.profitratio,
                profitpercent: data.sc.profitpercent,
                positionpercent: data.sc.positionpercent,
                highpremiums: data.sc.highpremium,
              },
              {
                name: 'Sell Put',
                marketvalue: data.sp.marketvalue,
                positionprofit: data.sp.onhandprofit,
                dayprofit: data.sp.todayprofit,
                historyprofit: data.sp.historyprofit,
                premiumscollect: data.sp.pendingpremium,
                profit: data.sp.profit,
                profitmarket: data.sp.profitratio,
                profitpercent: data.sp.profitpercent,
                positionpercent: data.sp.positionpercent,
                highpremiums: data.sp.highpremium,
              },
              {
                name: '总计：',
                marketvalue: data.sum.marketvalue,
                positionprofit: data.sum.onhandprofit,
                dayprofit: data.sum.todayprofit,
                historyprofit: data.sum.historyprofit,
                premiumscollect: data.sum.pendingpremium,
                profit: data.sum.profit,
                profitmarket: data.sum.profitratio,
                profitpercent: data.sum.profitpercent,
                positionpercent: data.sum.positionpercent,
                highpremiums: data.sum.highpremium,
              },
            ],
            code: res.code,
            columns: [
              {
                title: '',
                width: 80,
                dataIndex: 'name',
                type: 'string',
              },
              {
                title: '市值',
                width: 80,
                type: 'number',
                dataIndex: 'marketvalue',
              },
              {
                title: '持仓盈亏',
                width: 80,
                type: 'number',
                dataIndex: 'positionprofit',
              },
              {
                title: '当日盈亏',
                width: 80,
                type: 'number',
                dataIndex: 'dayprofit',
              },
              {
                title: '历史累计盈亏',
                width: 80,
                type: 'number',
                dataIndex: 'historyprofit',
              },
              {
                title: '待收权利金',
                width: 80,
                type: 'number',
                dataIndex: 'premiumscollect',
              },
              {
                title: '持仓+历史总收益',
                width: 110,
                type: 'number',
                dataIndex: 'profit',
              },
              {
                title: '盈利市值比',
                width: 80,
                type: 'number',
                dataIndex: 'profitmarket',
                render: (value, row, index) => {
                  return value === null ? null : (
                    <span>{NumberDivide(mathService.mul(value, 100), null, '%')}</span>
                  );
                },
              },
              {
                title: '总盈利百分比',
                width: 80,
                type: 'number',
                dataIndex: 'profitpercent',
                render: (value, row, index) => {
                  return value === null ? null : (
                    <span>{NumberDivide(mathService.mul(value, 100), null, '%')}</span>
                  );
                },
              },
              {
                title: '仓位占比',
                width: 80,
                type: 'number',
                dataIndex: 'positionpercent',
                render: (value, row, index) => {
                  return value === null ? null : (
                    <span>{NumberDivide(mathService.mul(value, 100), null, '%')}</span>
                  );
                },
              },
              {
                title: '高权利金',
                width: 80,
                type: 'number',
                dataIndex: 'highpremiums',
                render: (value, row, index) => {
                  return value === null ? null : (
                    <span>{NumberDivide(mathService.mul(value, 100), null, '%')}</span>
                  );
                },
              },
            ],
          },
        });
      },
    });
  }

  dataSourceChangeOptions(date) {
    const { dispatch } = this.props;
    const that = this;
    dispatch({
      type: 'fourfunds/GetFundFourValueOption',
      payload: {
        date,
      },
      callback: res => {
        that.setState({
          dataSourceSC: {
            title: `四号基金期权持仓Sell Call ${(res.data.scList[0].date || '').split(' ')[0]}`,
            code: 1,
            data: res.data.scList,
            total: ['profit', 'todayprofit', 'initpremium', 'curpremium', 'positionsize'],
            // paging:true,
            columns: [
              {
                title: '序号',
                width: 50,
                dataIndex: 'serialnumber',
                type: 'number',
              },

              {
                title: '类型',
                dataIndex: 'type',
                type: 'number',
                width: 50,
                render: (value, row, index) => {
                  if (value === 1) {
                    return 'SP';
                  }
                  if (value === 2) {
                    return 'SC';
                  }
                  if (value === 3) {
                    return 'BP';
                  }
                  if (value === 4) {
                    return 'BC';
                  }
                },
              },
              {
                title: '期权代码',
                dataIndex: 'optioncode',
                type: 'string',
                width: 160,
                render: (value, row, index) => {
                  let color;
                  if (row.riskflag === 1) {
                    color = '#ff4d4f';
                  }
                  return <span style={{ color }}>{value}</span>;
                },
              },
              {
                title: '执行价',
                width: 75,
                dataIndex: 'strikeprice',
                type: 'number',
              },
              {
                title: '当前价格',
                width: 75,
                dataIndex: 'nowprice',
                type: 'number',
              },
              {
                title: '距执行价幅度',
                width: 75,
                dataIndex: 'changerate',
                type: 'number',

                render: (value, row, index) => {
                  return <span>{NumberDivide(mathService.mul(value, 100), null, '%')}</span>;
                },
              },
              {
                title: '成本价',
                width: 75,
                dataIndex: 'premium',
                type: 'number',
              },
              {
                title: '期权现价',
                width: 75,
                dataIndex: 'cflast',
                type: 'number',
              },
              {
                title: '当日盈亏',
                width: 90,
                dataIndex: 'todayprofit',
                type: 'number',
              },
              {
                title: '盈亏金额',
                width: 90,
                dataIndex: 'profit',
                type: 'number',
              },
              {
                title: '初始权利金',
                width: 90,
                dataIndex: 'initpremium',
                type: 'number',
              },
              {
                title: '当前剩余权利金',
                width: 90,
                dataIndex: 'curpremium',
                type: 'number',
              },
              {
                title: '股数',
                width: 60,
                dataIndex: 'optioncount',
                type: 'number',
              },
              {
                title: '到期日',
                dataIndex: 'expiry',
                type: 'date',

                render: (value, row, index) => {
                  return <span>{typeof value === 'string' ? value.split(' ')[0] : ''}</span>;
                },
              },
              {
                title: '剩余天数',
                width: 60,
                dataIndex: 'dayleft',
                type: 'number',
              },
              {
                title: '头寸规模',
                width: 90,
                dataIndex: 'positionsize',
                type: 'number',
              },
              {
                title: '操作时间',
                dataIndex: 'tradedate',
                type: 'date',

                render: (value, row, index) => {
                  return <span>{typeof value === 'string' ? value.split(' ')[0] : ''}</span>;
                },
              },
            ],
          },
          dataSourceSP: {
            title: `四号基金期权持仓Sell Put ${(res.data.spList[0].date || '').split(' ')[0]}`,
            code: 1,
            data: res.data.spList,
            total: ['profit', 'todayprofit', 'initpremium', 'curpremium', 'positionsize'],
            // paging:true,
            columns: [
              {
                title: '序号',
                width: 50,
                dataIndex: 'serialnumber',
                type: 'number',
              },

              {
                title: '类型',
                dataIndex: 'type',
                type: 'number',
                width: 50,
                render: (value, row, index) => {
                  if (value === 1) {
                    return 'SP';
                  }
                  if (value === 2) {
                    return 'SC';
                  }
                  if (value === 3) {
                    return 'BP';
                  }
                  if (value === 4) {
                    return 'BC';
                  }
                },
              },
              {
                title: '期权代码',
                dataIndex: 'optioncode',
                type: 'string',
                width: 160,

                render: (value, row, index) => {
                  let color;
                  if (row.riskflag === 1) {
                    color = '#ff4d4f';
                  }
                  return <span style={{ color }}>{value}</span>;
                },
              },
              {
                title: '执行价',
                width: 75,
                dataIndex: 'strikeprice',
                type: 'number',
              },
              {
                title: '当前价格',
                width: 75,
                dataIndex: 'nowprice',
                type: 'number',
              },
              {
                title: '距执行价幅度',
                width: 75,
                dataIndex: 'changerate',
                type: 'number',

                render: (value, row, index) => {
                  return <span>{NumberDivide(mathService.mul(value, 100), null, '%')}</span>;
                },
              },
              {
                title: '成本价',
                width: 75,
                dataIndex: 'premium',
                type: 'number',
              },
              {
                title: '期权现价',
                width: 75,
                dataIndex: 'cflast',
                type: 'number',
              },
              {
                title: '当日盈亏',
                width: 90,
                dataIndex: 'todayprofit',
                type: 'number',
              },
              {
                title: '盈亏金额',
                width: 90,
                dataIndex: 'profit',
                type: 'number',
              },
              {
                title: '初始权利金',
                width: 90,
                dataIndex: 'initpremium',
                type: 'number',
              },
              {
                title: '当前剩余权利金',
                width: 90,
                dataIndex: 'curpremium',
                type: 'number',
              },
              {
                title: '股数',
                width: 60,
                dataIndex: 'optioncount',
                type: 'number',
              },
              {
                title: '到期日',
                dataIndex: 'expiry',
                type: 'date',

                render: (value, row, index) => {
                  return <span>{typeof value === 'string' ? value.split(' ')[0] : ''}</span>;
                },
              },
              {
                title: '剩余天数',
                width: 60,
                dataIndex: 'dayleft',
                type: 'number',
              },
              {
                title: '头寸规模',
                width: 90,
                dataIndex: 'positionsize',
                type: 'number',
              },
              {
                title: '操作时间',
                dataIndex: 'tradedate',
                type: 'date',

                render: (value, row, index) => {
                  return <span>{typeof value === 'string' ? value.split(' ')[0] : ''}</span>;
                },
              },
            ],
          },
        });
      },
    });
  }

  dataSourcechangeStock(date) {
    const { dispatch } = this.props;
    const that = this;
    dispatch({
      type: 'fourfunds/GetFundFourValueStock',
      payload: {
        date,
      },
      callback: res => {
        that.setState({
          dataSourceStock: {
            title: `四号基金股票持仓 ${(res.data[0].date || '').split(' ')[0]}`,
            code: 1,
            data: res.data,
            total: ['profit', 'todayprofit', 'initalvalue', 'curvalue', ['ubs', 'ctb', 'boc']],
            // paging:true,
            columns: [
              {
                title: '股票代码',
                dataIndex: 'code',
                type: 'string',
                width: 80,
              },
              {
                title: '买卖方向',
                dataIndex: 'type',
                type: 'number',
                width: 60,

                render: (value, row, index) => {
                  return <span>{value === 1 ? '空头' : value === 0 ? '多头' : null}</span>;
                },
              },
              {
                title: '成本价',
                width: 80,
                dataIndex: 'avgprice',
                type: 'number',
              },
              {
                title: '当前价格',
                width: 80,
                dataIndex: 'nowprice',
                type: 'number',
              },
              {
                title: '盈亏幅度',
                width: 80,
                dataIndex: 'profitpercent',
                type: 'number',

                render: (value, row, index) => {
                  return <span>{NumberDivide(value * 100, 2, '%')}</span>;
                },
              },
              {
                title: '盈亏金额',
                width: 100,
                dataIndex: 'profit',
                type: 'number',
              },
              {
                title: '当日盈亏',
                width: 100,
                dataIndex: 'todayprofit',
                type: 'number',
              },
              {
                title: '初始金额',
                width: 100,
                dataIndex: 'initalvalue',
                type: 'number',
              },
              {
                title: '当前金额',
                width: 100,
                dataIndex: 'curvalue',
                type: 'number',
              },

              {
                title: '瑞银',
                width: 60,
                dataIndex: 'ubs',
                type: 'number',

                render: (value, row, index) => {
                  const obj = {
                    children: NumberDivide(value),
                    props: {},
                  };
                  if (index === 0) obj.props.colSpan = 3;
                  return obj;
                },
              },
              {
                title: '花旗',
                width: 60,
                dataIndex: 'ctb',
                type: 'number',

                render: (value, row, index) => {
                  const obj = {
                    children: NumberDivide(value),
                    props: {},
                  };
                  if (index === 0) obj.props.colSpan = 0;
                  return obj;
                },
              },
              {
                title: '中银',
                width: 60,
                dataIndex: 'boc',
                type: 'number',

                render: (value, row, index) => {
                  const obj = {
                    children: NumberDivide(value),
                    props: {},
                  };
                  if (index === 0) obj.props.colSpan = 0;
                  return obj;
                },
              },
              {
                title: '可SC瑞银',
                width: 80,
                dataIndex: 'scubscount',
                type: 'number',
              },
              {
                title: '可Sell Call花旗',
                width: 90,
                dataIndex: 'scctbcount',
                type: 'number',
              },
              {
                title: '可Sell Call中银',
                width: 90,
                dataIndex: 'scboccount',
                type: 'number',
              },
              {
                title: '可Sell Call金额',
                width: 90,
                dataIndex: 'scvalue',
                type: 'number',
              },
              {
                title: '可Sell Call比例',
                width: 90,
                dataIndex: 'scpercent',
                type: 'number',

                render: (value, row, index) => {
                  return <span>{NumberDivide(mathService.mul(value, 100), null, '%')}</span>;
                },
              },
              /*  {
                  title: '止损价格',
                  width:80,
                  dataIndex: 'stoplossprice',
                  type:'number',

                },
                {
                  title: '未止损原因',
                  width:80,
                  dataIndex: 'reason',
                  type:'string',

                }, */
              {
                title: '开仓时间',
                width: 100,
                dataIndex: 'opendate',
                type: 'date',

                render: (value, row, index) => {
                  return <span>{typeof value === 'string' ? value.split(' ')[0] : ''}</span>;
                },
              },
            ],
          },
        });
      },
    });
  }

  rowSetKey(record, index) {
    if (record.ctbflag === 1) {
      return true;
    }
  }

  HtmlCrop() {
    const { dispatch } = this.props;
    const that = this;
    that.setState({
      cropFlag: true,
    });
    html2canvas(document.getElementById('crop'), {
      scale: 1,
    }).then(canvas => {
      const imgUrl = canvas.toDataURL();
      // dataURLtoFile(imgUrl, 'aaa')
      // 获取截图base64
      dispatch({
        type: 'fourfunds/CommitImage',
        payload: {
          base64Str: imgUrl,
          jobName: '',
        },
        callback: res => {
          that.setState({
            cropFlag: res,
          });
        },
      });
    });
  }

  getData(date) {
    const { dispatch } = this.props;
    dispatch({
      type: 'fourfunds/GetDateList',
    });
    this.dataSourceChangeDay(date);
    this.dataSourceChangeOptions(date);
    this.dataSourcechangeStock(date);
    /* 导入列表数据 */
    dispatch({
      type: 'fourfunds/GetWorth',
      payload: {
        date,
      },
    });
    dispatch({
      type: 'fourfunds/GetMonthWorth',
      payload: {
        date,
      },
    });
  }

  onSelectTime(e) {
    const that = this;
    that.getData(e);
  }

  render() {
    const { dataSourceDay, dataSourceSC, dataSourceSP, dataSourceStock, cropFlag } = this.state;
    const {
      loading,
      fourfunds: { charts, chartsMonth, selectDate },
    } = this.props;
    const { index } = this.state;
    const list = [];
    if (charts.length !== 0) {
      for (let i = 0; i < charts.length; i++) {
        list.push(
          <Col md={12} sm={24}>
            {charts[i].name === 'stock净值' ? (
              <TimelineChartFour
                height={350}
                data={charts[i].list}
                titleMap={{ y1: charts[i].name, y2: 'spy净值' }}
              />
            ) : (
              <TimelineChartFour
                height={350}
                data={charts[i].list}
                titleMap={{ y1: charts[i].name }}
              />
            )}
          </Col>
        );
      }
    }
    const listMonth = [];
    if (chartsMonth.length !== 0) {
      for (let i = 0; i < chartsMonth.length; i++) {
        listMonth.push(
          <Col md={12} sm={24}>
            {chartsMonth[i].name === 'stock月度净值' ? (
              <TimelineChartFourMonth
                height={350}
                data={chartsMonth[i].list}
                titleMap={{ y1: chartsMonth[i].name, y2: 'spy月度净值' }}
              />
            ) : (
              <TimelineChartFourMonth
                height={350}
                data={chartsMonth[i].list}
                titleMap={{ y1: chartsMonth[i].name }}
              />
            )}
          </Col>
        );
      }
    }
    const selectList = [];
    if (selectDate.length !== 0) {
      for (let i = 0; i < selectDate.length; i++) {
        selectList.push(
          <Option key={!selectDate[i] ? ' ' : selectDate[i].substring(0, 10)}>
            {!selectDate[i] ? ' ' : selectDate[i].substring(0, 10)}
          </Option>
        );
      }
    }
    return (
      <PageHeaderWrapper>
        <Row style={{ width: '100%', textAlign: 'right' }}>
          选择历史时间:
          <Select
            defaultValue="今日"
            style={{ width: 220, margin: ' 16px 30px 0px 12px' }}
            onChange={this.onSelectTime.bind(this)}
          >
            {selectList}
          </Select>
          {/* <DatePicker
            placeholder="请选择"
            style={{ width: 220, margin:' 16px 30px 0px 12px' }}
            onChange={this.onSelectTime.bind(this)}
          /> */}
          <span>
            <Button
              type="primary"
              onClick={this.HtmlCrop.bind(this)}
              loading={cropFlag}
              style={{ margin: ' 16px 30px 0px 12px', width: '9rem' }}
              ghost
            >
              截图上传
            </Button>
          </span>
        </Row>
        <Card id="crop" style={{ border: 0 }}>
          <StandardTablePro dataSource={dataSourceDay} closeScroll />
          <br />
          <br />
          {charts.length === 0 ? <Loading /> : <Row>{list}</Row>}
          <br />
          <br />
          {chartsMonth.length === 0 ? <Loading /> : <Row>{listMonth}</Row>}
          <br />
          <br />
          <StandardTablePro
            dataSource={dataSourceSC}
            rowSetKey={this.rowSetKey.bind(this)}
            closeScroll
          />
          <br />
          <br />
          <StandardTablePro
            dataSource={dataSourceSP}
            rowSetKey={this.rowSetKey.bind(this)}
            closeScroll
          />
          <br />
          <br />
          <StandardTablePro dataSource={dataSourceStock} closeScroll />
        </Card>
      </PageHeaderWrapper>
    );
  }

  componentDidMount() {
    this.getData('');
  }

  componentWillUnmount() {}
}

export default Summary;
